﻿//-----------------------------------------------------------------------
// <copyright file="UsageLogger.cs" company="Redmist">
//     Copyright (c) Damien T Smith. All rights reserved.
// </copyright>
// <author>Damien Smith</author>
//-----------------------------------------------------------------------

namespace Redmist.UsageMonitor.Controller
{
    using System;
    using System.IO;
    using Redmist.UsageMonitor.UsageData;

    /// <summary>Logs usage updates to a file in the current user's 'Documents' folder.</summary>
    public class UsageLogger
    {
        /// <summary>Initializes a log file writer using an existing log file or creating a new file with header if no file exists.</summary>
        /// <returns>A System.IO.StreamWriter representing an open log file ready for writing.</returns>
        public static StreamWriter InitializeLogFileWriter()
        {
            string logFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "aaNet_Usage_Log.txt");
            bool writeHeader = false;

            if (!File.Exists(logFile))
            {
                writeHeader = true;
            }

            StreamWriter logWriter = new StreamWriter(logFile, true);
            if (writeHeader)
            {
                WriteHeader(logWriter);
            }

            return logWriter;
        }

        /// <summary>Writes a usage data line based on the supplied usage data to the specified log file.</summary>
        /// <param name="logFile">A System.IO.StreamWriter representing an open log file ready for writing.</param>
        /// <param name="monthlyUsage">A Redmist.UsageMonitor.UsageData.MonthlyUsage representing monthly usage data.</param>
        public static void LogToFile(StreamWriter logFile, MonthlyUsage monthlyUsage)
        {
            logFile.WriteLine(string.Format(
                "{0},{1},{2},{3},{4},{5}",
                monthlyUsage.AnniversaryData.UsageLastUpdated.ToString(),
                monthlyUsage.DownloadStatistics.Peak,
                monthlyUsage.UploadStatistics.Peak,
                monthlyUsage.DownloadStatistics.CountedOffPeak,
                monthlyUsage.UploadStatistics.CountedOffPeak,
                monthlyUsage.PlanName));
        }

        /// <summary>Writes a monthly usage header using the specified StreamWriter.</summary>
        /// <param name="logWriter">A System.IO.StreamWriter representing an open log file ready for writing.</param>
        private static void WriteHeader(StreamWriter logWriter)
        {
            logWriter.WriteLine("Retrieved,PeakDownloads,PeakUploads,CountedOffPeakDownloads,CountedOffPeakUploads,Plan");
        }
    }
}
